import { createRouter, createWebHashHistory } from "vue-router"
import Layout from "@/layout/Layout.vue"
import { useUserStoreWithOut } from "@/store/modules/user"

export const MenuList = [
  {
    path: "/dashboard",
    name: "Dashboard",
    meta: {
      title: "首页",
    },
    component: () => import("@/views/dashboard/Dashboard.vue")
  },
  {
    path: "/authority",
    name: "Authority",
    meta: {
      title: "权限管理",
    },
    children: [
      {
        path: "/dept",
        name: "Dept",
        meta: {
          title: "部门管理",
        },
        component: () => import("@/views/dept/Dept.vue")
      },
      {
        path: "/user",
        name: "User",
        meta: {
          title: "用户管理",
        },
        component: () => import("@/views/user/User.vue")
      },
      {
        path: "/menu",
        name: "Menu",
        meta: {
          title: "菜单管理",
        },
        component: () => import("@/views/menu/Menu.vue")
      },
      {
        path: "/role",
        name: "Role",
        meta: {
          title: "角色管理",
        },
        component: () => import("@/views/role/Role.vue")
      },
      {
        path: "/permission",
        name: "Permission",
        meta: {
          title: "权限管理",
        },
        component: () => import("@/views/permission/Permission.vue")
      },
    ]
  },

]

const routes = [
  {
    path: "/",
    name: "Layout",
    component: Layout,
    children: MenuList
  },

  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/Login.vue")
  },
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})
export const setupRouter = (app: any) => {
  app.use(router)
}

router.beforeEach((to, _, next) => {
  const userStore = useUserStoreWithOut()
  if (userStore.access_token && userStore.userInfo) {
    if (to.path === '/login') {
      next({ path: "/user", replace: true })
    } else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})
